package com.msunsoft.support.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.msunsoft.common.Constants;
import com.msunsoft.system.mybatis.model.SysUser;

public class ShiroDbRealm extends AuthorizingRealm {

    private static final Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class);

    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        return null;
    }

    /**
     * 认证回调函数,登录时调用.
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String password = String.valueOf (token.getPassword ());
        String userName = String.valueOf (token.getUsername ());
        
        logger.debug ("用户：["+userName+":"+password+"]请求登录系统....");
        
        if (userName != null) {
            if (password.equals (userName)) {
                SysUser user = new SysUser ();
                user.setId (1);
                user.setName ("super");
                user.setPassword ("super");
                Subject currentUser = SecurityUtils.getSubject();
                Session session = currentUser.getSession();
                session.setAttribute(Constants.SESSION_USER, user);
                return new SimpleAuthenticationInfo (userName,password,getName ());
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

}
